#!/bin/bash

echo "🚀 启动物联网数据处理服务..."

# 检查是否安装了依赖
if [ ! -d "node_modules" ]; then
    echo "📦 安装依赖包..."
    pnpm install
fi

# 检查并创建环境配置文件
if [ ! -f ".env" ]; then
    echo "🔧 创建环境配置文件..."
    cat > .env << 'EOF'
# 服务器配置
PORT=3000
NODE_ENV=development

# MQTT 配置
MQTT_BROKER_URL=mqtt://localhost:1883
MQTT_CLIENT_ID=iot_data_processor
MQTT_USERNAME=
MQTT_PASSWORD=

# InfluxDB 配置
INFLUX_URL=http://localhost:8086
INFLUX_TOKEN=your_influx_token_here
INFLUX_ORG=your_org
INFLUX_BUCKET=iot_data

# 日志配置
LOG_LEVEL=info
EOF
    echo "✅ 已创建 .env 配置文件"
fi

# 编译TypeScript
echo "🔨 编译TypeScript..."
pnpm build

if [ $? -eq 0 ]; then
    echo "✅ 编译成功!"
    echo "🌟 项目已准备就绪!"
    echo ""
    echo "📋 可用命令:"
    echo "  pnpm dev     - 开发模式启动"
    echo "  pnpm start   - 生产模式启动"
    echo "  pnpm build   - 编译项目"
    echo ""
    echo "🔧 配置说明:"
    echo "  请编辑 .env 文件配置你的环境变量"
    echo "  - MQTT_BROKER_URL: MQTT代理地址"
    echo "  - INFLUX_URL: InfluxDB地址"
    echo "  - INFLUX_TOKEN: InfluxDB访问令牌"
    echo ""
    echo "🌐 API端点:"
    echo "  http://localhost:3000/health - 健康检查"
    echo "  http://localhost:3000/api/devices - 设备列表"
    echo ""
    echo "🚀 快速启动:"
    echo "  ./setup.sh && pnpm dev"
else
    echo "❌ 编译失败!"
    exit 1
fi
